1311E - Construct the Binary Tree - CodeForces Solution


brute force constructive algorithms trees *2200

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 5005;
int t, n, d, a[MAXN], cnt[MAXN], clv, ans[MAXN];
int main () {
	ios::sync_with_stdio (false);
	cin.tie (0);
	cin >> t;
	while (t--) {
		cin >> n >> d;
		d = -d;
		for (int i = 0;i < n;i++) {
			cnt[i] = 1;
			d += i;
		} 
		if (d < 0) {
			cout << "NO" << endl;
			continue;
		}
		clv = 1;
		for (int i = n - 1;i >= 1;i--) {
			if (d == 0) break;
			else if (d <= i - clv) {
				cnt[i - d]++;
				cnt[i]--;
//				cout << "Moving level " << i << " to level " << i - d << endl;
				d = 0; 
//				cout << "Got " << d << " more depth sum" << endl;
				break;
			}
			else {
				if (clv >= i) break;
				cnt[clv]++;
				cnt[i] = 0;
				d -= i - clv;
//				cout << "Moving level " << i << " to level " << clv << endl; 
//				cout << "Got " << d << " more depth sum" << endl;
				if (cnt[clv] >= (1 << clv)) clv++;
			}
		}
		if (d > 0) {
			cout << "NO" << endl;
			continue;
		}
		cout << "YES" << endl;
		int lst = 1, cnt2 = 1;
		for (int i = 1;i < n;i++) {
			for (int j = 1;j <= cnt[i];j++) {
				ans[++cnt2] = lst;
				if (j % 2 == 0) lst--;
			}
			lst = cnt2;
		}
		for (int i = 2;i <= n;i++) {
			cout << ans[i] << " ";
		}
		cout << endl;
		for (int i = 1;i <= n;i++) cnt[i] = 0;
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

981A - Antipalindrome
365A - Good Number
1204B - Mislove Has Lost an Array
1409D - Decrease the Sum of Digits
1476E - Pattern Matching
1107A - Digits Sequence Dividing
1348A - Phoenix and Balance
1343B - Balanced Array
1186A - Vus the Cossack and a Contest
1494A - ABC String
1606A - AB Balance
1658C - Shinju and the Lost Permutation
1547C - Pair Programming
550A - Two Substrings
797B - Odd sum
1093A - Dice Rolling
1360B - Honest Coach
1399C - Boats Competition
1609C - Complex Market Analysis
1657E - Star MST
1143B - Nirvana
1285A - Mezo Playing Zoma
919B - Perfect Number
894A - QAQ
1551A - Polycarp and Coins
313A - Ilya and Bank Account
1469A - Regular Bracket Sequence
919C - Seat Arrangements
1634A - Reverse and Concatenate
1619C - Wrong Addition